"""
项目管理API
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
from app.models.project import Project
from app.models.user import User
from app.models.team import Team
from app.utils.decorators import admin_required
from app.utils.validators import validate_project_data
from marshmallow import ValidationError

projects_bp = Blueprint('projects', __name__)

@projects_bp.route('/', methods=['GET'])
@jwt_required()
def get_projects():
    """获取项目列表"""
    try:
        current_user_id = get_jwt_identity()
        current_user = User.find_by_id(current_user_id)
        
        if not current_user:
            return jsonify({'error': '用户不存在'}), 404
        
        # 获取用户相关的项目
        projects = Project.get_user_projects(current_user_id)
        
        return jsonify({
            'projects': [project.to_dict() for project in projects]
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取项目列表失败: {str(e)}'}), 500

@projects_bp.route('/', methods=['POST'])
@jwt_required()
def create_project():
    """创建项目"""
    try:
        current_user_id = get_jwt_identity()
        current_user = User.find_by_id(current_user_id)
        
        if not current_user:
            return jsonify({'error': '用户不存在'}), 404
        
        data = request.get_json()
        
        # 验证数据
        try:
            validated_data = validate_project_data(data)
        except ValidationError as e:
            return jsonify({'error': '数据验证失败', 'details': e.messages}), 400
        
        # 检查团队权限（如果指定了团队）
        team_id = validated_data.get('team_id')
        if team_id:
            team = Team.find_by_id(team_id)
            if not team:
                return jsonify({'error': '团队不存在'}), 404
            
            if not team.is_member(current_user_id):
                return jsonify({'error': '无权限在此团队中创建项目'}), 403
        
        # 处理日期字段
        start_date = None
        end_date = None
        
        if validated_data.get('start_date'):
            try:
                from datetime import datetime
                start_date = datetime.fromisoformat(validated_data['start_date'])
            except ValueError:
                return jsonify({'error': '开始日期格式不正确'}), 400
        
        if validated_data.get('end_date'):
            try:
                from datetime import datetime
                end_date = datetime.fromisoformat(validated_data['end_date'])
            except ValueError:
                return jsonify({'error': '结束日期格式不正确'}), 400
        
        # 创建项目
        project = Project(
            name=validated_data['name'],
            description=validated_data.get('description', ''),
            owner_id=current_user_id,
            team_id=team_id,
            start_date=start_date,
            end_date=end_date
        )
        
        db.session.add(project)
        db.session.commit()
        
        return jsonify({
            'message': '项目创建成功',
            'project': project.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'创建项目失败: {str(e)}'}), 500

@projects_bp.route('/<int:project_id>', methods=['GET'])
@jwt_required()
def get_project(project_id):
    """获取项目详情"""
    try:
        current_user_id = get_jwt_identity()
        project = Project.find_by_id(project_id)
        
        if not project:
            return jsonify({'error': '项目不存在'}), 404
        
        # 检查用户是否有权限访问项目
        if not project.can_access(current_user_id):
            return jsonify({'error': '无权限访问此项目'}), 403
        
        return jsonify({
            'project': project.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取项目详情失败: {str(e)}'}), 500

@projects_bp.route('/<int:project_id>', methods=['PUT'])
@jwt_required()
def update_project(project_id):
    """更新项目信息"""
    try:
        current_user_id = get_jwt_identity()
        project = Project.find_by_id(project_id)
        
        if not project:
            return jsonify({'error': '项目不存在'}), 404
        
        # 检查用户是否有权限修改项目
        if project.owner_id != current_user_id:
            return jsonify({'error': '无权限修改此项目'}), 403
        
        data = request.get_json()
        
        # 验证数据
        try:
            validated_data = validate_project_data(data)
        except ValidationError as e:
            return jsonify({'error': '数据验证失败', 'details': e.messages}), 400
        
        # 更新项目信息
        project.name = validated_data['name']
        project.description = validated_data.get('description', '')
        
        # 更新团队（如果指定）
        team_id = validated_data.get('team_id')
        if team_id:
            team = Team.find_by_id(team_id)
            if not team:
                return jsonify({'error': '团队不存在'}), 404
            
            if not team.is_member(current_user_id):
                return jsonify({'error': '无权限将此项目分配给此团队'}), 403
            
            project.team_id = team_id
        
        # 更新日期字段
        if validated_data.get('start_date'):
            try:
                from datetime import datetime
                project.start_date = datetime.fromisoformat(validated_data['start_date'])
            except ValueError:
                return jsonify({'error': '开始日期格式不正确'}), 400
        elif 'start_date' in validated_data and validated_data['start_date'] is None:
            project.start_date = None
        
        if validated_data.get('end_date'):
            try:
                from datetime import datetime
                project.end_date = datetime.fromisoformat(validated_data['end_date'])
            except ValueError:
                return jsonify({'error': '结束日期格式不正确'}), 400
        elif 'end_date' in validated_data and validated_data['end_date'] is None:
            project.end_date = None
        
        db.session.commit()
        
        return jsonify({
            'message': '项目更新成功',
            'project': project.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'更新项目失败: {str(e)}'}), 500

@projects_bp.route('/<int:project_id>', methods=['DELETE'])
@jwt_required()
def delete_project(project_id):
    """删除项目"""
    try:
        current_user_id = get_jwt_identity()
        project = Project.find_by_id(project_id)
        
        if not project:
            return jsonify({'error': '项目不存在'}), 404
        
        # 检查用户是否有权限删除项目
        if project.owner_id != current_user_id:
            return jsonify({'error': '无权限删除此项目'}), 403
        
        db.session.delete(project)
        db.session.commit()
        
        return jsonify({
            'message': '项目删除成功'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'删除项目失败: {str(e)}'}), 500

@projects_bp.route('/<int:project_id>/tasks', methods=['GET'])
@jwt_required()
def get_project_tasks(project_id):
    """获取项目任务列表"""
    try:
        current_user_id = get_jwt_identity()
        project = Project.find_by_id(project_id)
        
        if not project:
            return jsonify({'error': '项目不存在'}), 404
        
        # 检查用户是否有权限访问项目
        if not project.can_access(current_user_id):
            return jsonify({'error': '无权限访问此项目'}), 403
        
        tasks = project.get_tasks()
        
        return jsonify({
            'tasks': [task.to_dict() for task in tasks]
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取项目任务失败: {str(e)}'}), 500

@projects_bp.route('/<int:project_id>/stats', methods=['GET'])
@jwt_required()
def get_project_stats(project_id):
    """获取项目统计信息"""
    try:
        current_user_id = get_jwt_identity()
        project = Project.find_by_id(project_id)
        
        if not project:
            return jsonify({'error': '项目不存在'}), 404
        
        # 检查用户是否有权限访问项目
        if not project.can_access(current_user_id):
            return jsonify({'error': '无权限访问此项目'}), 403
        
        stats = project.get_stats()
        
        return jsonify({
            'stats': stats
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取项目统计失败: {str(e)}'}), 500


